package com.text.demmongodb.task;

import com.text.demmongodb.entity.User;
import com.text.demmongodb.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName UserTask
 * @Author By wen
 * @Description
 * @Date 2023/10/30 15:23
 * @Version 1.0
 */
@Slf4j
@Component
public class UserTask {

    @Resource
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserMapper userMapper;

    @Scheduled(cron = "0 0/2 * * * ?")
    public void runimpl(){
        log.info("==>同步用户数据至数据库定时任务开始！");
        try {
            handler();
        } catch (Exception e) {
            log.error("==>定时任务执行异常：",e);
        }
        log.info("==>同步用户数据至数据库定时任务结束！");
    }

    public void handler() throws Exception{
        List<User> userList = userMapper.selectList();

        String collectionName = "user";
        if(null != userList && userList.size() > 0){
            userList.forEach(user -> {
                User save = mongoTemplate.save(user, collectionName);
                log.info("成功更新一条数据{}",save);
                User entity = new User();
                entity.setId(user.getId());
                userMapper.updateUser(entity);
            });
        }
    }
}
